package com.shiro.demo0929.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shiro.demo0929.entity.Role;
import com.shiro.demo0929.entity.User;
import com.shiro.demo0929.service.RoleService;
import com.shiro.demo0929.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 自定义的realm
 * @date 2020/9/29 19:42
 */

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权do...");

//        拿到当前用户
        Subject subject = SecurityUtils.getSubject();

//        取到当前用户的各种信息
        User currentUser = (User) subject.getPrincipal();

//        得到当前用户的权限集合
        List<String > roles = currentUser.getRoles();


//        创建设置权限的对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

//        将权限集合添加到对象中
        info.addStringPermissions(roles);

        return info;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("认证 do...");
//        执行认证逻辑
//        得到token
        UsernamePasswordToken userToken = (UsernamePasswordToken)token;

//        根据用户名查询信息
        User user = userService.getOne(new QueryWrapper<User>().eq("username", userToken.getUsername()));

//        执行判断逻辑（只需要认证用户名是否存在，密码认证让shiro来认证）
        if (StringUtils.isEmpty(user)){
//            这里返回为null会抛出UnknownAccountException异常
            return null;
        }

//        查出权限集合
        List<Role> roleUsers = roleService.list(new QueryWrapper<Role>().eq("role_user", user.getId()));

        List<String> userRoles = new ArrayList<>();

        for (Role role : roleUsers) {
            userRoles.add(role.getRoleName());
        }

//        将查出的集合添加到user对象中
        user.setRoles(userRoles);


//        将登录信息存放到session中
        Subject subject = SecurityUtils.getSubject();

        Session session = subject.getSession();

        session.setAttribute("loginUser",user);

//        密码加密，默认是md5
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
